from fastapi import APIRouter, Request, HTTPException, Response, UploadFile

import os, sys
import uuid
from datetime import datetime
import tempfile
from typing import Dict, List, Optional

from .funasr_service import do_audio_translations

from utils.FileUtil import fetch_file
from utils.MD5Util import compute_path_md5
from utils.VideoUtil import extract_audio_with_ffmpeg

from configs import config


# 定义路由信息
router = APIRouter(
    prefix='/video',
    tags = ['视频处理']
)

@router.post("/translations")
async def video_translations(request: Request):
    data = await request.json()

    video_url = data.get("video_url")

    video_url_md5 = compute_path_md5(video_url)

    video_dir = f"{config.setting.statics.path}/process/video/{video_url_md5}"
    os.makedirs(video_dir, exist_ok=True)

    audio_dir = f"{config.setting.statics.path}/process/audio/{video_url_md5}"
    os.makedirs(audio_dir, exist_ok=True)

    video_file = f"{config.setting.statics.path}/process/video/{video_url_md5}/video.mp4"
    audio_file = f"{config.setting.statics.path}/process/audio/{video_url_md5}/audio.m4a"
    audio_urls = f"{config.setting.statics.urls}/process/audio/{video_url_md5}/audio.m4a"

    if not os.path.exists(video_file):
        fetch_file(video_url, video_file)

    if os.path.exists(audio_file):
        os.remove(audio_file) # 删除旧的音频文件

    extract_audio_with_ffmpeg(video_file, audio_file)

    if os.path.exists(audio_file):
        result = do_audio_translations(audio_file=audio_file, merge_sentences=True, merge_short_sentences=True)
        result["audio_urls"] = audio_urls
        return result

    return {
        "status": "failure", 
        "message": "音频提取失败"
    }